package com.ptswitch.material.pages.contract;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.upload.services.UploadedFile;
import org.slf4j.Logger;

import com.ptswitch.material.model.contract.ContractAttachment;
import com.ptswitch.material.pages.base.MaterialBasePage;
import com.ptswitch.material.service.ContractAttachmentService;
import com.ptswitch.material.util.HlogConstants;

public class AddAttachment extends MaterialBasePage {
    @Inject
    private Logger logger;
    @Inject
    private ContractAttachmentService uploadSer;
    @Property
    private String contractId;
    @Property
    private List<UploadedFile> files;
    @InjectPage
    private ViewContract viewContract;

    @OnEvent(value = EventConstants.ACTIVATE)
    Object toAddAttachment(String id) {
        checkUserIsLogin();
        contractId = id;
        files = new ArrayList<UploadedFile>();
        return null;
    }

    @OnEvent(value = EventConstants.PASSIVATE)
    Object onPassivate() {
        return contractId;
    }

    @OnEvent(value = EventConstants.SUCCESS)
    Object addAttachment() {
        checkUserIsLogin();
        List<ContractAttachment> uploads = getWebUtil().upload(files, ContractAttachment.class);
        for (ContractAttachment upload : uploads) {
            upload.setOwnerId(contractId);
            upload.setUser(getVisitor());
            uploadSer.save(upload);
            hlog(HlogConstants.addUpload, upload);
        }
        return viewContract.initialize(contractId);
    }
}